<?php

class UsersController extends Controller
{
	public function actionRegister(){
		if(!Yii::app()->user->isGuest)
		{
			jsonOut(array(
				'error'=>false,
				'message'=>'User logged'
			));
		}
		$model=new Users;
		
		if(!empty($_POST)){
			$model->email = $_POST['email'];
			$model->first_name = $_POST['first_name'];
			$model->username = $_POST['username'];
			$model->last_name = $_POST['last_name'];
			$model->password = $_POST['password'];
			$groupUser = Groups::model()->findByAttributes(array('level'=>1));
			$model->group_id = $groupUser->id;

			if($model->validate()){
				if(trim($_POST['confirm_password'])==""){
					jsonOut(array(
						'error'=>true,
						'model'=>array(
							'confirm_password'=>array('Confirm Password cannot be blank.')
						),
						'message'=>'Register failer'
					));
				}
				if($model->password != $_POST['confirm_password']){
					jsonOut(array(
						'error'=>true,
						'model'=>array(
							'confirm_password'=>array('Confirm Password must be repeated exactly.')
						),
						'message'=>'Register failer'
					));
				}
				
				$model->password = Users::model()->encodePassword($model->password);
				$model->created = date("Y-m-d G:i:s");
				if($model->save()){
					$model->forceLoginByEmail($model->email,true);
					jsonOut(array(
						'error'=>false,
						'message'=>'Register successfully'
					));
				}else{
					jsonOut(array(
						'error'=>true,
						'model'=>$model->getErrors(),
						'message'=>'Register failer'
					));
				}
			}else{
				jsonOut(array(
					'error'=>true,
					'model'=>$model->getErrors(),
					'message'=>'Register failer'
				));
			}
			
			
		}else{
		
		}
		jsonOut(array(
			'error'=>true,
			'data'=>$_POST
		));
	}
	public function actionLogin()
	{
		$model = new FormLogin;
		
		// $page = Yii::app()->request->getParam('page',null);
		if(!Yii::app()->user->isGuest)
		{
			jsonOut(array(
				'error'=>false,
				'message'=>'User logged'
			));
		}
		// if it is ajax validation request

		if(!empty($_POST)){
			$model->email = $_POST['email'];
			$model->password = $_POST['password'];
			// $model->remember = $_POST['remember'];
			
			if($model->validate() && $model->login()){
				
				jsonOut(array(
					'error'=>false,
					'message'=>'User logged'
				));
				
			}else{
				jsonOut(array(
					'error'=>true,
					'model'=>$model->getErrors(),
					'message'=>'Login failer'
				));
			}
		}
	}
}